package com.wcgksoft.source;


import com.jnrsmcu.sdk.netdevice.*;
import com.wcgksoft.entity.ZData.*;
import com.wcgksoft.service.BasicDataService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;

import javax.servlet.ServletContext;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

//@Component
public class DataCollection implements InitializingBean, ServletContextAware {

  //@Autowired
  //private BasicDataService basicDataService;
  @Autowired
  private BasicDataService basicDataService;
  private RSServer rsServer;// 定义监听服务对象
  private IDataListener listener = new IDataListener() {

    @Override
    public void receiveTimmingAck(TimmingAck data) {// 校时指令应答处理
      System.out.println("校时应答->设备编号:" + data.getDeviceId() + "\t执行结果："
              + data.getStatus() + "\r\n");
    }

    @Override
    public void receiveTelecontrolAck(TelecontrolAck data) {// 遥控指令应答处理
      System.out.println("遥控应答->设备编号:" + data.getDeviceId() + "\t继电器编号:"
              + data.getRelayId() + "\t执行结果:" + data.getStatus() + "\r\n");
    }

    @Override
    public void receiveStoreData(StoreData data) {// 已存储数据接收处理
      // 遍历节点数据。数据包括网络设备的数据以及各个节点数据。温湿度数据存放在节点数据中
      for (NodeData nd : data.getNodeList()) {
        SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
        String str = sdf.format(nd.getRecordTime());

        System.out.println("存储数据->设备地址:" + data.getDeviceId() + "\t节点:"
                + nd.getNodeId() + "\t温度:" + nd.getTem() + "\t湿度:"
                + nd.getHum() + "\t存储时间:" + str + "\t坐标类型：" + nd.getCoordinateType() + "\t经度:" + nd.getLng() + "\t纬度：" + nd.getLat() + "\r\n");


      }

    }

    @Override
    public void receiveRealtimeData(RealTimeData data) {// 实时数据接收处理
      // 遍历节点数据。数据包括网络设备的数据以及各个节点数据。温湿度数据存放在节点数据中
      for (NodeData nd : data.getNodeList()) {
        try {
          BasicData data1 = new BasicData();
          data1.setAcquisitiontime(new Date());
          if (nd.getNodeId() == 1) {
            data1.setCom("通道" + nd.getNodeId());
            data1.setData(nd.getTem() + "");
            data1.setNo(data.getDeviceId() + "");
            data1.setHmdata(nd.getHum() + "");
            data1.setDatatype("wd");
            basicDataService.save(data1);
            BasicData data2 = new BasicData();
            data2.setAcquisitiontime(new Date());
            data2.setCom("通道" + nd.getNodeId());
            data2.setData(nd.getHum() + "");
            data2.setNo(data.getDeviceId() + "");
            data2.setHmdata(nd.getHum() + "");
            data2.setDatatype("sd");
            basicDataService.save(data2);
          } else if (nd.getNodeId() == 2) {
            data1.setCom("通道" + nd.getNodeId());
            data1.setData((nd.getHum() * 10) + "");
            data1.setNo(data.getDeviceId() + "");
            data1.setHmdata((nd.getHum() * 10) + "");
            data1.setDatatype("gzqd");
            basicDataService.save(data1);
          } else if (nd.getNodeId() == 3) {
            data1.setCom("通道" + nd.getNodeId());
            data1.setData((nd.getHum() * 10) + "");
            data1.setNo(data.getDeviceId() + "");
            data1.setHmdata((nd.getHum() * 10) + "");
            data1.setDatatype("co2");
            basicDataService.save(data1);
          } else if (nd.getNodeId() == 4) {
            data1.setCom("通道" + nd.getNodeId());
            data1.setData(nd.getHum() + "");
            data1.setNo(data.getDeviceId() + "");
            data1.setHmdata(nd.getHum() + "");
            data1.setDatatype("aq");
            basicDataService.save(data1);
          } else if (nd.getNodeId() == 5) {
            data1.setCom("通道" + nd.getNodeId());
            data1.setData(nd.getHum() + "");
            data1.setNo(data.getDeviceId() + "");
            data1.setHmdata(nd.getHum() + "");
            data1.setDatatype("fs");
            basicDataService.save(data1);
          } else {
            data1.setCom("通道" + nd.getNodeId());
            data1.setData(nd.getTem() + "");
            data1.setNo(data.getDeviceId() + "");
            data1.setHmdata(nd.getHum() + "");
            data1.setDatatype("");
            basicDataService.save(data1);
          }
        } catch (Exception e) {
          System.out.println("------------------数据接收异常异常信息如下👇------------------");
          System.out.println(e.getMessage());
          System.out.println(e);
        }


        // basicDataService.save(data1);
        System.out.println("实时数据->设备地址:" + data.getDeviceId() + "\t节点:"
                + nd.getNodeId() + "\t温度:" + nd.getTem() + "\t湿度:"
                + nd.getHum() + "\t经度：" + data.getLng() + "\t纬度："
                + data.getLat() + "\t坐标类型：" + data.getCoordinateType()
                + "\t继电器状态" + data.getRelayStatus() + "\t浮点型数据："
                + nd.getFloatValue() + "\t32位有符号数据："
                + nd.getSignedInt32Value() + "\t32位无符号数据："
                + nd.getUnSignedInt32Value() + "\r\n");
      }

    }

    @Override
    public void receiveLoginData(LoginData data) {// 登录数据接收处理
      System.out.println("登录->设备地址:" + data.getDeviceId() + "\r\n");

    }

    @Override
    public void receiveParamIds(ParamIdsData data) {
      String str = "设备参数编号列表->设备编号：" + data.getDeviceId() + "\t参数总数量："
              + data.getTotalCount() + "\t本帧参数数量：" + data.getCount()
              + "\r\n";
      for (int paramId : data.getPararmIdList())// 遍历设备中参数id编号
      {
        str += paramId + ",";
      }
      System.out.println(str + "\r\n");

    }

    @Override
    public void receiveParam(ParamData data) {
      String str = "设备参数->设备编号：" + data.getDeviceId() + "\r\n";

      for (ParamItem pararm : data.getParameterList()) {
        str += "参数编号："
                + pararm.getParamId()
                + "\t参数描述："
                + pararm.getDescription()
                + "\t参数值："
                + (pararm.getValueDescription() == null ? pararm
                .getValue() : pararm.getValueDescription().get(
                pararm.getValue())) + "\r\n";
      }
      System.out.println(str + "\r\n");

    }

    @Override
    public void receiveWriteParamAck(WriteParamAck data) {
      String str = "下载设备参数->设备编号：" + data.getDeviceId() + "\t参数数量："
              + data.getCount() + "\t"
              + (data.isSuccess() ? "下载成功" : "下载失败");
      System.out.println(str + "\r\n");

    }

    @Override
    public void receiveTransDataAck(TransDataAck data) {
      String str = "数据透传->设备编号：" + data.getDeviceId() + "\t响应结果："
              + data.getData() + "\r\n字节数：" + data.getTransDataLen();
      System.out.println(str + "\r\n");

    }
  };


  @Override
  public void afterPropertiesSet() throws Exception {
    System.out.println("***等待采集设备初始化端口（19221）***");
    new Thread(new Runnable() {

      @Override
      public void run() {

        rsServer = RSServer.Initiate(Integer.parseInt("19225"));// 初始化

        rsServer.addDataListener(listener);// 添加数据监听事件
        try {
          rsServer.start();
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }// 启动监听服务
      }
    }).start();
  }

  @Override
  public void setServletContext(ServletContext servletContext) {

  }


}


